<!-- eslint-disable vue/no-mutating-props -->
<script lang="ts" setup>
import { Dialog, showConfirmDialog, showFailToast, showToast } from 'vant'
import lodash from 'lodash'
import LxButton from '../../common/LxButton.vue'
import MaterialPick from './MaterialPick.vue'
import QuantityInput from './QuantityInput.vue'
import { MaterialModel, OrderItemModel, OrderModel } from '~/model'
import { ItemRecommendModel } from '~/model/ItemRecommendModel'

const props = defineProps<{
  order: OrderModel
}>()

// 订单修改会话框
const dialogChangeIndex = ref(-1)
const dialogChangeItemVisible = ref(false)
const dialogChangeQuantityVisible = ref(false)

// 商品列表
// const recommendModel = new ItemRecommendModel()
const recommendModel = ref(null as (ItemRecommendModel | null))

function dialogChangeItem(i: number) {
  dialogChangeIndex.value = i
  dialogChangeItemVisible.value = true
}

function dialogChangeQuantity(i: number) {
  dialogChangeIndex.value = i
  dialogChangeQuantityVisible.value = true
}

// 修改单价相关
const dialogChangeUnitPriceVisible = ref(false)
const inputDialogUnitpriceEl = ref(null as any)
const inputDialogUnitprice = ref(0)
function dialogChangeUnitPrice(i: number) {
  dialogChangeIndex.value = i
  dialogChangeUnitPriceVisible.value = true
  inputDialogUnitprice.value = props.order.items[i].unitPrice
  setTimeout(() => {
    inputDialogUnitpriceEl.value.focus()
    inputDialogUnitpriceEl.value.select()
  }, 50)
}
function onConfirmUnitprice() {
  props.order.items[dialogChangeIndex.value].unitPrice = inputDialogUnitprice.value
}

function wantToChangeAmount() {
  showToast('金额是自动计算的')
}

function handleDeleteItem(i: number) {
  // 如果还没有进行选择，则不进行判断
  if (!props.order.items[i].material || props.order.items[i].material!.id < 0) {
    deleteItem(i)
    return
  }

  showConfirmDialog({
    message: '确定要删除条目吗',
  })
    .then(() => {
      deleteItem(i)
    })
}

function deleteItem(i: number) {
  props.order.items.splice(i, 1)
}

const imgSrc = ref(null as any)

function cellClick(row: OrderItemModel, coln: number) {
  // const property: string = col.property
  const index = props.order.items.indexOf(row)
  // console.log(index)
  if (coln === 0) {
    dialogChangeItem(index)
  }
  else if (coln === 1) {
    dialogChangeQuantity(index)
  }
  else if (coln === 2) {
    dialogChangeUnitPrice(index)
  }
  else if (coln === 3) {
    wantToChangeAmount()
  }
}

function handleAdd() {
  props.order.items.push(new OrderItemModel())
  dialogChangeItem(props.order.items.length - 1)
}

function calcGetter(i: number) {
  const pre = props.order.items.slice(0, i)
  lodash.reverse(pre)
  if (recommendModel.value === null) {
    return async () => []
  }
  else {
    return () => recommendModel.value!.recommand(i, pre, props.order.consumer)
  }
}

function calcQuantityGetter(i: number) {
  const chain = props.order.items.slice(0, i + 1)
  lodash.reverse(chain)

  if (recommendModel.value === null) {
    return () => []
  }
  else {
    return () => recommendModel.value!.recommandQuantity!(i, chain, props.order.consumer)
  }
}

function onChooseItem(item: OrderItemModel) {
  // 查看是否商品已经有了
  const exist = props.order.items.find(x => x.material?.id === item.material?.id)
  if (exist) {
    // 判断重复操作、重复选择、切换位置
    const existIndex = props.order.items.indexOf(exist)

    // 重复操作
    if (existIndex === dialogChangeIndex.value) {
      // do nothing
    }
    else {
      // 重复选择
      if (props.order.items[dialogChangeIndex.value].material === undefined) {
        showFailToast('已经存在这个商品了')
      }
      // 切换位置
      else {
        showToast('交换了商品次序')
        const t = props.order.items[existIndex]
        props.order.items[existIndex] = props.order.items[dialogChangeIndex.value]
        props.order.items[dialogChangeIndex.value] = t
      }
    }
  }
  else {
    // 切换商品
    const _item = props.order.items[dialogChangeIndex.value]
    _item.material = item.material
    _item.unitPrice = item.unitPrice

    // 计算默认数量
    const getQuantity = calcQuantityGetter(dialogChangeIndex.value)
    const quantities = getQuantity()
    console.log('quantities', quantities)
    item.quantity = quantities[0]?.quantity ?? 0
    _item.quantity = item.quantity
    _item.autoAmount()
  }
}

function getRecommendData() {
  console.log('getRecommendData.....');
  recommendModel.value = new ItemRecommendModel(props.order.consumer!)
  recommendModel.value.init()
}

onMounted(() => {
  getRecommendData()
})

const orderWatchable = computed(() => {
  return JSON.parse(JSON.stringify(props.order)) as OrderModel
})

watch(orderWatchable, (val, oldVal) => {
  if (val.consumer?.id !== oldVal.consumer?.id) {
    getRecommendData()
  }
}, {
  deep: true,
})
</script>

<template>
  <div ref="imgSrc" mb paper of-hidden p0>
    <MaterialPick
      v-if="recommendModel"
      v-model:show="dialogChangeItemVisible"
      :current="order.items[dialogChangeIndex]?.material"
      :source-getter="calcGetter(dialogChangeIndex)"
      @delete="handleDeleteItem(dialogChangeIndex)"
      @update:item="onChooseItem"
    />
    <QuantityInput
      v-if="recommendModel"
      v-model:show="dialogChangeQuantityVisible"
      :row="order.items[dialogChangeIndex]"
      :quantity-arr-getter="calcQuantityGetter(dialogChangeIndex)"
    />
    <Dialog
      v-model:show="dialogChangeUnitPriceVisible"
      title="商品单价"
      :show-cancel-button="true"
      @confirm="onConfirmUnitprice"
    >
      <input
        ref="inputDialogUnitpriceEl"
        v-model="inputDialogUnitprice"
        type="number"
        w-full b-none text-center lh-10
      >
    </Dialog>

    <table class="lx-table lx-table-large">
      <thead>
        <tr
          :style="{
            backgroundColor: 'dodgerblue',
            color: 'white',
          }"
        >
          <td>名称/规格</td>
          <td text-right>
            数量
          </td>
          <td text-right>
            单价
          </td>
          <td>金额</td>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in order.items" :key="index">
          <td @click="cellClick(item, 0)">
            {{ item.material?.name }}/{{ item.material?.specification }}
          </td>
          <td text-right @click="cellClick(item, 1)">
            {{ item.quantity }}
          </td>
          <td text-right @click="cellClick(item, 2)">
            {{ item.unitPrice }}
          </td>
          <td @click="cellClick(item, 3)">
            {{ item.amount }}
          </td>
        </tr>
      </tbody>
    </table>

    <LxButton
      icon="plus"
      title="添加商品"
      :action="handleAdd"
      h-12 w-full b-rd-0
      color="white"
      text-color="dodgerblue"
    />
  </div>
</template>

<style scoped>

</style>
